<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

class TradeOnlineOrder extends Base
{
    protected function trade(): object
    {
        return $this->hasOne(TradeOnline::class, 'id', 'trade_id')
            ->field('id,sn');
    }

    protected function buyer(): object
    {
        return $this->hasOne(User::class, 'id', 'buyer_id')
            ->field('id,code,nickname,mobile,photo');
    }

    protected function seller(): object
    {
        return $this->hasOne(User::class, 'id', 'seller_id')
            ->field('id,code,nickname,mobile,photo');
    }

    protected function getAccountAttr($value): string
    {
        return get_pay_way($value);
    }

    public static function add($param, $user, $system): array
    {
        parent::startTrans();
        try {
            if (empty($system['trade_online_open'])) {
                throw new \Exception('交易功能已关闭');
            }
            if (!empty($system['trade_online_min'])) {
                if ($system['trade_online_min'] > $param['amount']) {
                    throw new \Exception('最低交易数量：' . $system['trade_online_min']);
                }
            }
            if (!empty($system['trade_online_bs']) && $system['trade_online_bs'] > 1) {
                if (intval($param['amount']) % intval($system['trade_online_bs']) != 0) {
                    throw new \Exception('交易倍数：' . $system['trade_online_bs']);
                }
            }
            if (md5($param['pay_password']) != $user->pay_password) {
                throw new \Exception('支付密码错误');
            }
            $info = TradeOnline::where(['id' => $param['id'], 'status' => 1])->lock(true)->find();
            if (empty($info)) {
                throw new \Exception('该交易不存在或已完成');
            }
            if ($info->uid == $user->id) {
                throw new \Exception('无法与自己进行交易');
            }
            if ($param['amount'] > $info->surplus_amount) {
                throw new \Exception('该交易剩余数量不足');
            }
            $account = $info->getData('account');
            $currency = round($param['amount'] * $info->price, 2);
            if ($info->type_id == 1) {
                if ($currency > $user->assets->currency) {
                    throw new \Exception(get_pay_way('currency') . '账户余额不足');
                }
                $buyer_id = $user->id;
                $seller_id = $info->uid;
                Target::Account()->basics($buyer_id, 'currency', $currency, '交易买入', '-')
                    ->createNormal($seller_id);
                Target::Account()->basics($buyer_id, $account, $param['amount'], '交易买入', '+')
                    ->createNormal($seller_id);
                Target::Account()->basics($seller_id, 'currency', $currency, '交易卖出', '+')
                    ->createNormal($buyer_id);
            } else {
                $cost_rate = 0;
                if (!empty($system['trade_online_cost']) && $system['trade_online_cost'] > 0) {
                    $cost_rate = $system['trade_online_cost'];
                }
                $real_amount = round($param['amount'] * (1 + $cost_rate), 2);
                if ($real_amount > $user->assets->$account) {
                    throw new \Exception(get_pay_way($account) . '账户余额不足');
                }
                $buyer_id = $info->uid;
                $seller_id = $user->id;
                Target::Account()->basics($seller_id, $account, $real_amount, '交易卖出', '-')
                    ->createNormal($buyer_id);
                Target::Account()->basics($seller_id, 'currency', $currency, '交易卖出', '+')
                    ->createNormal($buyer_id);
                Target::Account()->basics($buyer_id, $account, $param['amount'], '交易买入', '+')
                    ->createNormal($seller_id);
            }
            parent::create([
                'sn' => 'T' . date('YmdHis') . rand(100000, 999999) . $user->id,
                'trade_id' => $param['id'],
                'buyer_id' => $buyer_id,
                'seller_id' => $seller_id,
                'account' => $account,
                'amount' => $param['amount'],
                'price' => $info->price,
                'real_amount' => $currency
            ]);
            $info->surplus_amount -= $param['amount'];
            if ($info->surplus_amount <= 0) {
                $info->status = 2;
                $info->finish_time = time();
            }
            $info->save();
            parent::commit();

            return ['code' => 1, 'msg' => '交易成功'];
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}